<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addList="addList" />
    <!-- 主体部分 -->
    <TodoMain
      :list="renderList"
      @delList="delList"
      @changeStatus="changeStatus"
      @changeAll="changeAll"
    />
    <!-- 底部部分 -->
    <TodoFooter
      :list="list"
      @clearAll="clearAll"
      @filterList="filterList"
      :type="type"
    />
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'

export default {
  components: {
    TodoFooter,
    TodoHeader,
    TodoMain,
  },

  data() {
    return {
      list:
        [
          { id: 1, name: '吃饭', isDone: true },
          { id: 2, name: '睡觉', isDone: false },
          { id: 3, name: '打豆豆', isDone: true },
        ] || JSON.parse(localStorage.getItem('TodoListData')),
      type: 'ALL',
    }
  },
  methods: {
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    changeStatus(id) {
      const res = this.list.find((item) => item.id === id)
      res.isDone = !res.isDone
    },

    addList(listName) {
      const obj = {
        id: Date.now(),
        name: listName,
        isDone: false,
      }

      this.list = [...this.list, obj]
    },

    clearAll() {
      this.list = this.list.filter((item) => !item.isDone)
    },

    filterList(type) {
      this.type = type
    },

    changeAll(flag) {
      this.list = this.list.map((item) => {
        item.isDone = flag
        return item
      })
    },
  },

  computed: {
    renderList() {
      switch (this.type) {
        case 'ALL':
          return this.list
        case 'ACTIVE':
          return this.list.filter((item) => !item.isDone)
        case 'COMPLETED':
          return this.list.filter((item) => item.isDone)
        default:
          return this.list
      }
    },
  },

  watch: {
    list: {
      handler(value) {
        localStorage.setItem('TodoListData', JSON.stringify(value))
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>

<style></style>
